package com.zhuchaooasystem.ui.home.service;

import android.Manifest;
import android.content.pm.PackageManager;
import android.graphics.Color;
import android.support.v4.app.ActivityCompat;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;

import com.baidu.location.BDLocation;
import com.baidu.location.BDLocationListener;
import com.baidu.location.LocationClient;
import com.baidu.mapapi.map.BaiduMap;
import com.baidu.mapapi.map.BitmapDescriptor;
import com.baidu.mapapi.map.BitmapDescriptorFactory;
import com.baidu.mapapi.map.MapStatus;
import com.baidu.mapapi.map.MapStatusUpdateFactory;
import com.baidu.mapapi.map.MapView;
import com.baidu.mapapi.map.MyLocationConfiguration;
import com.baidu.mapapi.map.MyLocationData;
import com.hwangjr.rxbus.RxBus;
import com.zhuchaooasystem.R;
import com.zhuchaooasystem.base.BaseActivity;
import com.zhuchaooasystem.common.Key;
import com.zhuchaooasystem.entity.ServiceSignEntity;
import com.zhuchaooasystem.event.ServiceDetailEvent;
import com.zhuchaooasystem.presenter.home.servicesign.ServiceSignContract;
import com.zhuchaooasystem.presenter.home.servicesign.ServiceSignPresenter;
import com.zhuchaooasystem.utils.ScreenUtils;
import com.zhuchaooasystem.utils.ToastUtil;

import butterknife.BindView;
import butterknife.OnClick;

public class ServiceSignActivity extends BaseActivity<ServiceSignPresenter> implements ServiceSignContract.View {
    @BindView(R.id.actionbar_relative_rootview)
    RelativeLayout relative_rootview;
    @BindView(R.id.actionbar_iv_back)
    ImageView iv_back;
    @BindView(R.id.actionbar_txt_right)
    TextView txt_right;
    @BindView(R.id.actionbar_txt_title)
    TextView txt_title;
    //----
    @BindView(R.id.act_service_sign_mapview)
    MapView mapview;
    @BindView(R.id.act_service_sign_txt_address)
    TextView txt_address;
    //----
    private BaiduMap baiduMap;
    private LocationClient locationClient;
    private BitmapDescriptor bitmap_marker;
    private MyLocationConfiguration config;
    //----
    private int serviceid;
    private double longitude, latitude; //经纬度
    private String address;  //定位的地址

    @Override
    protected int getLayout() {
        return R.layout.activity_service_sign;
    }

    @Override
    protected ServiceSignPresenter getPresenter() {
        return new ServiceSignPresenter(mContext, this);
    }

    @Override
    protected void initVariables() {
        if (null != getIntent() && null != getIntent().getExtras()) {
            serviceid = getIntent().getExtras().getInt("serviceid");
        }
        //----
        bitmap_marker = BitmapDescriptorFactory.fromResource(R.drawable.ic_location);
        locationClient = new LocationClient(mContext.getApplicationContext());
        baiduMap = mapview.getMap();
        // 设置定位图层的配置（定位模式，是否允许方向信息，用户自定义定位图标）
        config = new MyLocationConfiguration(MyLocationConfiguration.LocationMode.FOLLOWING, true, bitmap_marker);
    }

    @Override
    protected void initView() {
        setActionbar();
        //权限
        if (ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_FINE_LOCATION) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.READ_PHONE_STATE) != PackageManager.PERMISSION_GRANTED
                && ActivityCompat.checkSelfPermission(this, Manifest.permission.ACCESS_COARSE_LOCATION) != PackageManager.PERMISSION_GRANTED) {
            //请求权限
            requestPermission(new String[]{Manifest.permission.ACCESS_FINE_LOCATION, Manifest.permission.ACCESS_COARSE_LOCATION,Manifest.permission.READ_PHONE_STATE}, Key.LOCATION);
        } else {
            setData();
        }

    }

    private void setData() {
        // 开启定位图层
        baiduMap.setMyLocationEnabled(true);
        baiduMap.setMyLocationConfigeration(config);
        //设置地图初始的缩放比例
        baiduMap.setMapStatus(MapStatusUpdateFactory.newMapStatus(new MapStatus.Builder().zoom(20).build()));
        //----
        locationClient.setLocOption(mPresenter.getLocationClientOption());
        locationClient.registerLocationListener(new BDLocationListener() {
            @Override
            public void onReceiveLocation(BDLocation bdLocation) {
                if (null != bdLocation) {
                    initBdLocation(bdLocation);
                }
            }

            private void initBdLocation(BDLocation bdLocation) {
                address = bdLocation.getAddrStr() + " " + bdLocation.getLocationDescribe();
                latitude = bdLocation.getLatitude();
                longitude = bdLocation.getLongitude();
                //----
                txt_address.setText(address);
                // 设置定位数据
                baiduMap.setMyLocationData(new MyLocationData.Builder()
                        .latitude(latitude)
                        .longitude(longitude).build());
            }
        });
    }

    private void setActionbar() {
        relative_rootview.setBackgroundColor(getResources().getColor(R.color.color_77000000));
        iv_back.setImageResource(R.drawable.ic_back_circle);
        iv_back.setPadding(ScreenUtils.dip2px(mContext, 10), ScreenUtils.dip2px(mContext, 10), ScreenUtils.dip2px(mContext, 10), ScreenUtils.dip2px(mContext, 10));
        iv_back.setVisibility(View.VISIBLE);
        txt_right.setText("打卡");
        txt_right.setTextColor(Color.WHITE);
        txt_right.setVisibility(View.VISIBLE);
        txt_title.setTextColor(Color.WHITE);
        txt_title.setText(getString(R.string.actionbar_title_sign_now));
    }

    @Override
    protected void initDataAndLoadData() {
        //开始定位
        locationClient.start();
    }

    @OnClick({R.id.actionbar_iv_back, R.id.actionbar_txt_right})
    public void onClick(View view) {
        switch (view.getId()) {
            //返回
            case R.id.actionbar_iv_back:
                finish();
                break;
            //打卡
            case R.id.actionbar_txt_right:
                if (TextUtils.isEmpty(address)) {
                    ToastUtil.showShort(mContext, "获取位置中，请稍候...");
                } else {
                    mPresenter.showDialog();
                }
                break;
        }
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //在activity执行onDestroy时执行mMapView.onDestroy()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onDestroy();
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        //在activity执行onResume时执行mMapView. onResume ()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onResume();
        }
    }

    @Override
    public void onPause() {
        super.onPause();
        //在activity执行onPause时执行mMapView. onPause ()，实现地图生命周期管理
        if (null != mapview) {
            mapview.onPause();
        }
    }

    @Override
    public String getAddress() {
        return address;
    }

    @Override
    public double getLatitude() {
        return latitude;
    }

    @Override
    public double getLongitude() {
        return longitude;
    }

    @Override
    public int getServiceid() {
        return serviceid;
    }

    @Override
    public void signFinish(ServiceSignEntity.ResultBean entity) {
        if (null != entity.getSuccessful()) {
            ToastUtil.showShort(mContext, entity.getSuccessful());
            RxBus.get().post("RedactToDetail", new ServiceDetailEvent());
            finish();
        } else {
            ToastUtil.showShort(mContext, entity.getError());
        }
    }


    /**
     * 权限成功回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionSuccess(int requestCode) {
        super.permissionSuccess(requestCode);
        switch (requestCode) {
            case Key.LOCATION:
                setData();
                break;
        }
    }

    /**
     * 权限失败回调函数
     *
     * @param requestCode
     */
    @Override
    public void permissionFail(int requestCode) {
        super.permissionFail(requestCode);
        Toast.makeText(mContext, "获取权限失败", Toast.LENGTH_SHORT).show();
    }


}
